<template>
	<view class="aifw">
		<navbar title='Ai法务'>
			<view @click="showGptMenu" class="hright" slot="right">
				<image class="menu" src="/static/images/menu.png" mode="" />
			</view>
		</navbar>
		<scroll-view scroll-y :scroll-top="scrollTop" id="scroll_view" class="scroll_view">
			<view id="list" class="list">
				<view class="item" v-for="item in msg_list">
					<view class="item_view ask">
						<view class="user_info">
							<image :src="avatar" class="avatar"></image>
							<view class="name">{{nickname}}</view>
						</view>
						<view class="item_text">
							<zero-markdown-view :markdown="item.message" themeColor="#fff"></zero-markdown-view>
							<image mode="widthFix" :src="item.images" v-if="item.images"></image>
						</view>
					</view>
					<view class="item_view answer" v-if="item.answer">
						<view class="user_info">
							<image src="@/static/img/tou.png" class="avatar"></image>
							<view class="name">Ai法务</view>
						</view>
						<view class="item_text">
							<zero-markdown-view :markdown="item.answer" themeColor="#fff"></zero-markdown-view>
						</view>
						<view class="oper">
							<view class="oper_item" @click.stop="stop_msg(item)" v-if="item.is_have">
								<image src="@/static/images/btn3.png"></image>
							</view>
							<view class="oper_item" @click="copy(item.answer)">
								<image src="@/static/images/copy2.png"></image>
							</view>
						</view>
					</view>
				</view>
			</view>
		</scroll-view>
		<view class="footer">
			<view class="content">
				<textarea class="textarea" v-model="msg" :auto-height="true" :maxlength="-1"
					:disable-default-padding="true" placeholder="请问您想咨询什么呢？"></textarea>
				<!-- <view class="upload" @click="uploadImage" v-if="model_id==2">
					<image src="@/static/images/upload2.png"></image>
				</view> -->
			</view>
			<view class="send" @click="submit">
				<image src="@/static/images/send.png"></image>
			</view>
		</view>
		<GptMenu ref="popupRef" @change="change" @delete="menu_delete"></GptMenu>
	</view>
</template>

<script>
	import GptMenu from "@/components/GptMenu/GptMenu"; 
	// const baseApiUrl = import.meta.env.VITE_BASE_URL;
	export default {
		data() {
			return {
				scrollTop: 0,
				msg: "",
				// 获取的值备份
				model_id_val: 2,
				group_id_val: "",
				chat_id: "",
				queryInfo: {
					chat_model_id: "",
					group_id: ""
				},
				name: "",
				msg_list: [],
				source: null,
				baseApiUrl: "https://lawyer.bitidea.cn",
				// 弹窗显示
				moreshow: false,
				images: "",
				nickname: "",
				avatar: "",
			}
		},
		onLoad() {
			this.getuserinfo();
			this.queryInfo.model_id = this.model_id_val = 2;
			this.queryInfo.group_id = this.group_id_val = "";
			this.chat_id = "";
			this.get_once();
		},
		onUnload() {
			if (!this.source) return;
			this.source.close();
			this.source = null;
		},
		mounted() {},
		methods: {
			async getuserinfo(){
				let res = await this.$u.api.userinfo({});
				this.avatar = res.user.head_portrait;
				this.nickname = res.user.nickname;
			},
			get_once() {
				this.$u.api.get_once(this.queryInfo).then(res => {
					console.log('res', res);
					this.name = res.chat_model.name;
					this.msg_list = res.list;
					this.group_id = res.group_id;
					this.scrollToBottom();
					if (!this.chat_id) {
						return false
					};
					this.send_eventSource();
				})
			},
			getHistory() {
				this.$u.api.chatIndex(this.queryInfo).then(res => {
					this.msg_list = res.list;
					this.group_id = res.group_id;
					this.scrollToBottom();
				})
				
			},
			scrollToBottom() {
				setTimeout(() => {
					const query = uni.createSelectorQuery().in(this);
					query.select('#scroll_view').boundingClientRect();
					query.select('#list').boundingClientRect();
					query.exec(res => {
						let h1 = res[0].height;
						let h2 = res[1].height;
						if (h2 <= h1) return false;
						this.scrollTop = h2 - h1 + 60;
					});
				}, 0);
			},
			send_eventSource() {
				this.source = new EventSource(`${this.baseApiUrl}/api/chat/stream?id=${this.chat_id}`);
				let item = this.msg_list.at(-1);
				item.answer = "";
				item.is_have = true;
				this.source.onmessage = res => {
					if (res.data == '[DONE]') {
						this.source.close();
						this.source = null;
						item.is_have = false;
						return false;
					}
					try{
						let data = JSON.parse(res.data);
						let delta = data?.choices[0].delta;
						let content = delta?.content;
						if (content && content != "null") {
							item.answer += content;
							this.scrollToBottom();
						}
					}catch(e){
						//TODO handle the exception
						console.log('e', e);
					}
					
				};
				this.source.onerror = () => {
					this.source.close();
					this.source = null;
					item.is_have = false;
				};
			},
			uploadImage(){
				uni.chooseImage({
					success: async (res) => {
						let tempFilePaths = res.tempFilePaths;
						let filePath = tempFilePaths[0];
						let {
							src
						} = await upload({
							filePath
						});
						images = src;
					}
				})
			},
			showGptMenu() {
				this.$refs.popupRef.show()
			},
			async submit(){
				if (this.source) {
					this.$u.toast('请等待回复完毕');
					return false;
				}
				if (!this.msg) {
					this.$u.toast("请输入内容");
					return false;
				}
				let content = this.msg;
				this.msg = "";
				let res = await this.$u.api.chatSend({
					chat_model_id: this.model_id,
					group_id: this.group_id,
					content,
					images: this.images
				});
				this.msg_list.push({
					message: content,
					images: this.images,
					answer: "",
					is_have: true
				})
				this.scrollToBottom();
				this.images = "";
				if (!this.queryInfo.group_id) {
					this.queryInfo.group_id = res.group_id;
				}
				this.chat_id = res.chat_id;
				console.log('res', res);
				console.log('this.chat_id', this.chat_id);
				this.send_eventSource();
			},
			// 暂停生成
			stop_msg(item){
				this.source.close();
				this.source = null;
				item.is_have = false;
			},
			// 复制
			copy(data) {
				uni.setClipboardData({
					data: data,
					showToast: false,
					success: () =>  {
						this.$u.toast('复制成功');
					}
				})
			},
			change(item){
				this.queryInfo.model_id = item?.chat_model_id ? String(item?.chat_model_id) : this.model_id_val;
				this.queryInfo.group_id = item?.id ? String(item?.id) : this.group_id_val;
				this.$refs.popupRef.close();
				this.getHistory();
			},
			menu_delete(id){
				if (id != this.queryInfo.group_id) return false;
				this.queryInfo.group_id = "";
				this.msg_list = [];
			}
		}
	}
</script>

<style lang="scss" scoped>
	page {
		background-color: #f5f5f5;
	}

	.aifw {
		.hright {
			.menu {
				width: 40rpx;
				height: 40rpx;
			}
		}

		.scroll_view {
			height: calc(100vh - #{$navBarHeight} - 100rpx);

			.list {
				padding: 100rpx 30rpx;
				box-sizing: border-box;

				.item {
					margin-bottom: 50rpx;

					&:last-child {
						margin-bottom: 0;
					}

					.item_view {
						&.ask {}

						&.answer {
							padding-top: 50rpx;
							box-sizing: border-box;

							.oper {
								padding-top: 40rpx;
								box-sizing: border-box;
								display: flex;
								justify-content: flex-end;
								align-items: center;

								.oper_item {
									width: 40rpx;
									height: 40rpx;
									margin-left: 40rpx;

									image {
										width: 100%;
										height: 100%;
									}
								}
							}
						}

						.user_info {
							display: flex;
							align-items: center;

							.avatar {
								width: 48rpx;
								height: 48rpx;
								border-radius: 50%;
							}

							.name {
								color: #333;
								font-size: 30rpx;
								padding-left: 22rpx;
								box-sizing: border-box;
							}
						}

						.item_text {
							line-height: 48rpx;
							color: #999;
							font-size: 30rpx;
							padding-left: 70rpx;

							:deep() {
								.zero-markdown-view {
									margin: 0 !important;
									padding: 0;
								}

								div,
								li,
								p {
									color: #FFFFFF !important;
								}
							}

							image {
								max-width: 100%;
							}
						}
					}
				}
			}
		}

		.footer {
			width: 100%;
			min-height: 100rpx;
			padding: 14rpx 30rpx;
			box-sizing: border-box;
			background: #fff;
			display: flex;
			justify-content: space-between;
			align-items: center;
			position: fixed;
			left: 0;
			bottom: 0;
			z-index: 2;

			.content {
				flex: 1;
				width: 580rpx;
				border-radius: 36rpx;
				padding: 0 30rpx;
				box-sizing: border-box;

				background: #f1f1f1;
				overflow: hidden;
				display: flex;
				align-items: center;


				.textarea {
					flex: 1;
					color: #999999;
					font-size: 28rpx;
					padding: 20rpx;
					box-sizing: content-box;
					max-height: 180rpx;

					:deep() {
						.uni-textarea-wrapper {
							max-height: 180rpx;
						}
					}
				}

				.upload {
					width: 40rpx;
					height: 40rpx;

					image {
						width: 100%;
						height: 100%;
					}
				}
			}

			.send {
				width: 100rpx;
				height: 60rpx;
				padding-left: 40rpx;
				box-sizing: border-box;

				image {
					width: 100%;
					height: 100%;
				}
			}
		}
	}
</style>